<style>
/*Computer Style*/
	input[type="text"]{
		max-width: 130px;
		margin-right: 5px;
	}
	textarea {
		min-width: 300px;
		min-height: 50px;
		max-width: 900px;
	}
	.closedForm,
	#registration,
	div#payLater,
	#end{
		display: none;
	}
	#switches{
		margin: 10px 0px 10px 0px;
	}
	input[maxlength='2']{
		width:20px;
	}
	input[maxlength='3']{
		width:30px;
	}
	input[maxlength='4']{
		width:40px;
	}
	input#email{
		width:200px;
	}
	div.multi-holder{
		display: inline-block;
		width: auto;
		background-color: #e7e7e7;
		padding: 5px;
		margin: 10px;
	}
	h6#message{
		color:red;
	}
	a.fakeLink{
		cursor: pointer;
	}
	table#calculator{
		width: auto;
	}
	td.bottomLine{
		border-top: 1px solid black;
	}
	div.floatRightFunction{
		float: right;
		margin-right:5px;
		cursor: pointer;
		display: inline-block;
	}
	div.eventListener{
		display: inline-block;
	}
	.noPlaceholder{
		margin-left: 5px;
	}
	.incomplete{
		background-color: #ffcccc;
	}
	td{
		padding: 2px;
	}
	.openForm{
		display: block;
	}
	#submit{
		margin-top: 10px;
	}
	#defferPayment{
		margin: 10px 0px 10px 0px;
	}
</style>
<script type="text/javascript">
	var formsData;
	var registration = makeRegistrationObject();
	$(document).ready(function(){
		loadRegform();
	});
	function makeRegistrationObject(){
		var obj = new Object;
		obj.costPerPerson = <?if (!empty($costPerPerson)) echo $costPerPerson; else echo 0;?>;
		obj.costPerCouple = <?if (!empty($costPerCouple)) echo $costPerCouple; else if (!empty($costPerPerson)) echo $costPerPerson*2; else echo 0;?>;
		obj.maxCost = <?if (!empty($maxCost)) echo $maxCost; else echo "null";?>;
		obj.emailTimer = null;
		obj.attendeeCount = 0;
		obj.basePrice = 0;
		obj.fee = 0;
		obj.coverFee = true;
		obj.grandTotal = 0;
		obj.defferPayment = false;
		return obj;
	}
	function loadRegform(){
		$.get("/registration/request.php?id=<?echo $id;?>&data=eventData&time="+(new Date()), function(res){
			formsData = res.split("|row|");
			formsData.shift();
			for (x in formsData){
				formsData[x] = formsData[x].split("|cell|");
				formsData[x][6] = formsData[x][6].split("\n");
				for (y in formsData[x][6]){
					formsData[x][6][y] = formsData[x][6][y].split(", ");
				}
			}
			console.log(formsData);
			printForm();
		});
	}
	function printForm(){
		for (x in formsData){
			$("#switches").append("<option>"+formsData[x][4]+"</option>");
			$("#forms").append("<form class='closedForm' id='"+formsData[x][4]+"'></form>");
			for (y in formsData[x][6]){
				if (formsData[x][6][y][5] == "1"){
					$("form#"+formsData[x][4]).append("<br><br>");
				}
				if (formsData[x][6][y][4] == "start"){
					$("form#"+formsData[x][4]).append("<span id='startMulti'>");
				}
				$("form#"+formsData[x][4]).append("<span class='noPlaceholder'>"+formsData[x][6][y][0]+": </span>");
				$("form#"+formsData[x][4]).append("<input type='"+formsData[x][6][y][2]+"' name='"+formsData[x][6][y][1]+"' class='"+formsData[x][6][y][3]+"' placeholder='"+formsData[x][6][y][0]+"' />"); 
				if (formsData[x][6][y][4] == "end"){
					$("form#"+formsData[x][4]).append("<span id='endMulti'>");;
				}
			}
		}
		$("#switches").change(function(event){
			showOption($("#switches").find(":selected").index());
		});
		$("input[type='email']").each(function(){
			$(this).replaceWith("<input type='text' name='"+$(this).attr("name")+"' class='"+$(this).attr("class")+"' placeholder='"+$(this).attr("placeholder")+"' onkeyup='validateEmail(this)'/>");
		});
		$("input[type='date']").each(function(){
			$(this).replaceWith("<input type='text' name='"+$(this).attr("name")+"' class='"+$(this).attr("class")+"' placeholder='"+$(this).attr("placeholder")+"' onkeyup='validateDate(this)'/>");
		});
		$("input[name='phone']").each(function(){
			var str = "Phone: ";
			str += "<input type='text' name='"+$(this).attr("name")+"' class='"+$(this).attr("class")+"' maxlength='3' onkeyup='autoTab(this)'>";
			str += " - ";
			str += "<input type='text' name='"+$(this).attr("name")+"' class='"+$(this).attr("class")+"' maxlength='3' onkeyup='autoTab(this)'>";
			str += " - ";
			str += "<input type='text' name='"+$(this).attr("name")+"' class='"+$(this).attr("class")+"' maxlength='4'>";
			$(this).replaceWith(str);
		});
		$("input[type='textarea']").each(function(){
			$(this).replaceWith("<textarea name='"+$(this).attr("name")+"' class='"+$(this).attr("class")+"' placeholder='"+$(this).attr("placeholder")+"'>");
		});
		$("span#startMulti").each(function(){
			$(this).nextUntil("span#endMulti").wrapAll("<div id='firstClone' class='multi-holder'>");
			$(".multi-holder:last").wrap("<div class='clone-holder'>");
			$(".multi-holder:last").append("<br><br><div class='floatRightFunction' onclick='addNewAttendee();'>+ add more</div>");
			$(".clone-holder:last").prepend("<h4>Attendees</h4>");
			$("span#startMulti:first").remove();
			$("span#endMulti:first").remove();
		});
		initPage();
	}
	function initPage(){
		showOption(0);
		if (formsData.length == 1){
			$("#switches").replaceWith("<br>");
		}
		updatePrice();
		$(".fakeLink").click(function(){$("#registration").toggle()});
	}
	function addNewAttendee(){
		var clone = $(".openForm").find("#firstClone").clone(true);
		clone.removeAttr("id");
		clone.children().each(function(){
			$(this).val(null);
			$(this).removeClass("incomplete");
			if ($(this).hasClass("floatRightFunction")){
				$(this).remove();
			}
		});
		clone.append("<div class='floatRightFunction' onclick='deleteExtraAttendee($(this).parent())'>Delete</div>");
		clone.appendTo($(".openForm").find(".clone-holder"));
		updatePrice();
	}
	function deleteExtraAttendee(box){
		box.remove();
		updatePrice();
	}
	function makeMysqlVars(){
		var x = $(".openForm").index();
		var id = formsData[x][1];
		var vars = new Array(id);
		for (y in formsData[x][6]){
			var Values = "";
			$(".openForm").find("[name="+formsData[x][6][y][1]+"]").each(function(index){
				if (index > 0){
					if (formsData[x][6][y][1] == "phone"){
						Values+=".";
					} else {
						Values+="|multi|";
					}
				}
				Values += encodeURIComponent($(this).val());
			});
			vars.push(Values);
		}
		if (registration.defferPayment){
			vars.push(0, 0, "Defered", "false");
		} else {
			vars.push(1, 0, "Paypal");
			vars.push(registration.coverFee);
		}
		return vars.join("|cell|");
	}
	function confirmInfo(vars){
		var x = $(".openForm").index();
		vars = vars.split("|cell|");
		var id = vars.shift();
		var confirmation = "";
		for (var y=0;y<formsData[x][6].length;y++){
			if (formsData[x][6][y][4] == "start"){
				var personCount = vars[y].split("|multi|").length;
				for (var z=0;z<personCount;z++){
					var i = y;
					while (formsData[x][6][i][4] != "no"){
						var multiVars = vars[i].split("|multi|");
						if (z == 0){
							confirmation += formsData[x][6][i][0]+": "+ decodeURIComponent(multiVars[z])+"\n";
						} else {
							confirmation += formsData[x][6][i][0]+" "+(z+1)+": "+ decodeURIComponent(multiVars[z])+"\n";
						}
						i++;
					}
					confirmation += "\n";
				}
				y = i;
			} else {
				confirmation += formsData[x][6][y][0]+": "+ decodeURIComponent(vars[y])+"\n";
			}
		}
		return confirmation;
	}
	function submitRegistration(){
		if (!validateRequired()){
			return false;
		}
		var mysqlVars = makeMysqlVars();
		if (!confirm("Please confirm your information:\n\n"+confirmInfo(mysqlVars))){
			return false;
		}
		$.get("/registration/insert.php?vars=" + mysqlVars, function(res){
			$("form").trigger("reset");
			$("#registration").hide();
			$("#message").html(res);
		});
	}
	function autoTab(obj){
		if (obj.value.length == obj.maxLength && !isNaN(obj.value)){
			obj.nextSibling.nextSibling.focus();
		}
	}
	function validateEmail(obj){
		clearTimeout(registration.emailTimer);
		if (obj.value != null && obj.value != ""){
			if ((obj.value.search(/^.+@.+\..+$/) == -1)){
				registration.emailTimer = setTimeout(function(){
					$(obj).addClass("incomplete");
				}, 2000);
			} else {
				$(obj).removeClass("incomplete");
			}
		} else {
			$(obj).removeClass("incomplete");
		}
	}
	function validateDate(obj){
		if (obj.value != null && obj.value != ""){
			if ((obj.value.search(/^[0-9]+\-[0-9]+\-[0-9]+$/) >= 0)){
				return 0;
			}
			var dateFormatter = new Date(obj.value);
			if (isNaN(dateFormatter.getMonth())){
				obj.value = "";
			} else{
				obj.value = (dateFormatter.getMonth()+1) +"-"+ dateFormatter.getDate() +"-"+ dateFormatter.getFullYear();
			}
		}
	}
	function validateRequired(){
		var valid = true;
		$(".openForm").find("input[type='text'], textarea").each(function(){
			if ($(this).val().search(/[\/\<\>]/) >= 0){
				alert("Fields cannot contain / > < characters");
				$(this).addClass("incomplete");
				valid = false;
			} else {
				$(this).removeClass("incomplete");
			}
			if ($(this).hasClass("required")){
				if ($(this).val() == ""){
					$(this).addClass("incomplete");
					valid = false;
				} else {
					$(this).removeClass("incomplete");
				}
			}
		});
		return valid;
	}
	function calculateBasePrice(){
		if (registration.attendeeCount%2 == 0){
			registration.basePrice = (registration.attendeeCount/2) * registration.costPerCouple;
		} else {
			registration.basePrice = ((registration.attendeeCount - 1)/2) * registration.costPerCouple;
			if (registration.costPerPerson != 0){
				registration.basePrice += registration.costPerPerson;
			} else {
				registration.basePrice += registration.costPerCouple;
			}
		}
		if (registration.maxCost != null){
			if (registration.basePrice >= registration.maxCost){
				registration.basePrice = registration.maxCost;
			}
		}
	}
	function calculateFee(){
		registration.fee = ((registration.basePrice*.022)+.30);
	}
	function calculateGrandTotal(){
		if (registration.coverFee && (!registration.defferPayment)){
			registration.grandTotal = parseFloat(registration.basePrice) + parseFloat(registration.fee);
		} else {
			registration.grandTotal = registration.basePrice;
		}
	}
	function updatePrice(){
		registration.attendeeCount = $(".openForm").find(".eventListener").length;
		calculateBasePrice();
		calculateFee();
		calculateGrandTotal();
		$("#basePrice").text(registration.basePrice.toFixed(2));
		$("#fee").text(registration.fee.toFixed(2));
		$("#grandTotal").text(registration.grandTotal.toFixed(2));
	}
	function updateFeeCovered(obj){
		registration.coverFee = $(obj).attr("checked");
		updatePrice();
	}
	function updateDefferPayment(i){
		if (!i){
			registration.defferPayment = false;
			$("#calculator").find("tr:lt(2)").show();
			updatePrice();
		} else {
			registration.defferPayment = true;
			$("#calculator").find("tr:lt(2)").hide();
			updatePrice();
		}
	}
	function showOption(val){
		$(".openForm").removeClass("openForm").addClass("closedForm");
		$("#forms").find("form:eq("+val+")").removeClass("closedForm").addClass("openForm");
		if (formsData[val][2] == "1"){
			$("#defferPayment").show();
			updateDefferPayment($("#defferPayment").find(":selected").index());
		} else {
			$("#defferPayment").val(0);
			updateDefferPayment($("#defferPayment").find(":selected").index());
			$("#defferPayment").hide();
		}
		if (formsData[val][3] == "1"){
			$("#coverFee").show();
			updateFeeCovered($("#coverFee").find("input"));
		} else {
			$("#coverFee").find("input").attr("checked", "checked");
			updateFeeCovered($("#coverFee").find("input"));
			$("#coverFee").hide();
		}
		$("#end").show();
		$("#initialChoice").remove();
		updatePrice();
	}
</script>
<a class='fakeLink'>
	<h4 id='displayForm'>Register For Event</h4>
<?
if (!empty($costPerPerson)){
	printf(" Cost per person: $%s\n", number_format($costPerPerson, 2));
}
if (!empty($costPerCouple)){
	printf("Cost per couple: $%s\n", number_format($costPerCouple, 2));
}
if (!empty($maxCost)){
	printf("Maximum cost per family: $%s\n", number_format($maxCost, 2));
}
?>
</a>
<div id='registration'>
	<select id='switches'></select>
	<div id='forms'></div>
	<div id='end'>
		<select id='defferPayment' onchange="updateDefferPayment(this.selectedIndex)">
			<option>Pay Online</option>
			<option>Pay at will call</option>
		</select>
		<table id='calculator'>
			<tr>
				<td>Base Price</td>
				<td>$</td>
				<td id='basePrice'>0.00</td>
			</tr>
			<tr id=''>
				<td>Fee</td>
				<td>$</td>
				<td id='fee'>0.00</td>
				<td id='coverFee'><input type='checkbox' onclick='updateFeeCovered(this)' checked="checked"> Cover fee</td>
			</tr>
			<tr id=''>
				<td class='bottomLine'>Grand Total</td>
				<td class='bottomLine'>$</td>
				<td class='bottomLine' id='grandTotal'>0.00</td>
			</tr>
		</table>
		<button id='submit' onclick="submitRegistration()">Submit</button>
	</div>
</div>
<h6 id='message'><?echo $_REQUEST['message'];?></h6>                                                                           